package com.lysb.core.utils;

/**
 * 字节转换工具类
 *
 * @author Zengzhong on 2022/5/24
 */
public class BytesUtils {

    private static final char[] DIGITS = "0123456789ABCDEF".toCharArray();

    /**
     * 高效写法 16进制字符串转成byte数组
     *
     * @param hex 16进制字符串，支持大小写
     * @return byte数组
     */
    public static byte[] hexStringToBytes(String hex) {
        byte[] result = new byte[hex.length() / 2];
        char[] chars = hex.toCharArray();
        for (int i = 0, j = 0; i < result.length; i++) {
            result[i] = (byte) (toByte(chars[j++]) << 4 | toByte(chars[j++]));
        }
        return result;
    }

    /**
     * 高效写法 byte数组转成16进制字符串
     *
     * @param bytes byte数组
     * @return 16进制字符串
     */
    public static String bytesToHexString(byte[] bytes) {
        char[] buf = new char[bytes.length * 2];
        int c = 0;
        for (byte b : bytes) {
            buf[c++] = DIGITS[(b >> 4) & 0x0F];
            buf[c++] = DIGITS[b & 0x0F];
        }
        return new String(buf);
    }

    private static int toByte(char c) {
        if (c >= '0' && c <= '9') {
            return (c - '0');
        } else if (c >= 'A' && c <= 'F') {
            return (c - 'A' + 0x0A);
        } else if (c >= 'a' && c <= 'f') {
            return (c - 'a' + 0x0a);
        }
        throw new RuntimeException("invalid hex char '" + c + "'");
    }
}